// src/stores/windows.js - 选项式 API
import { defineStore } from 'pinia'

export const useWindowsStore = defineStore('windows', {
  state: () => ({
    windows: [],
    activeWindowId: null,
  }),

  getters: {
    windowCount: (state) => state.windows.length,
    activeWindow: (state) => state.windows.find((win) => win.id === state.activeWindowId),
    mainWindow: (state) => state.windows.find((win) => win.type === 'main'),
    childWindows: (state) => state.windows.filter((win) => win.type === 'child'),
    isElectron: () => !!(window.electronAPI && typeof window.electronAPI === 'object'),
  },

  actions: {
    async openRouteWindow(route, title = '新窗口', options = {}) {
      if (!this.isElectron) {
        window.location.hash = route
        return
      }

      const defaultOptions = {
        width: 800,
        height: 600,
        title: title,
        route: route,
        ...options,
      }

      try {
        const safeOPtions = JSON.parse(JSON.stringify(defaultOptions))
        const result = await window.electronAPI.openNewWindow(safeOPtions)
        console.log('窗口打开成功:', result)
        await this.refreshWindowsList()
        return result
      } catch (error) {
        console.error('打开窗口失败:', error)
        throw error
      }
    },

    async openURLWindow(url, title = '网页') {
      if (!this.isElectron) {
        window.open(url, '_blank')
        return
      }

      try {
        await window.electronAPI.openNewWindow({
          width: 1200,
          height: 800,
          title: title,
          url: url,
        })
        await this.refreshWindowsList()
      } catch (error) {
        console.error('打开 URL 窗口失败:', error)
        throw error
      }
    },

    async openDebugWindow(route, title = '调试窗口', options = {}) {
      const debugOptions = {
        width: 1200,
        height: 800,
        title: title,
        route: route,
        openDevTools: true,
        ...options,
      }

      try {
        const result = await window.electronAPI.openNewWindow(debugOptions)
        console.log('调试窗口打开成功:', result)
        await this.refreshWindowsList()
        return result
      } catch (error) {
        console.error('打开调试窗口失败:', error)
        throw error
      }
    },

    async closeWindow(windowId) {
      if (!this.isElectron) return false

      try {
        const success = await window.electronAPI.closeWindow(windowId)
        if (success) {
          await this.refreshWindowsList()
        }
        return success
      } catch (error) {
        console.error('关闭窗口失败:', error)
        return false
      }
    },

    async refreshWindowsList() {
      if (!this.isElectron) return
      try {
        const windowList = await window.electronAPI.getWindowsInfo()
        this.windows = windowList

        // 更新活跃窗口
        if (windowList.length > 0 && !this.activeWindowId) {
          this.activeWindowId = windowList[0].id
        }
        console.log('窗口列表已刷新:', this.windows)
      } catch (error) {
        console.error('获取窗口列表失败:', error)
      }
    },

    setActiveWindow(windowId) {
      if (this.windows.some((win) => win.id === windowId)) {
        this.activeWindowId = windowId
      }
    },

    async focusWindow(windowId) {
      if (!this.isElectron) return

      try {
        await window.electronAPI.focusWindow(windowId)
        this.setActiveWindow(windowId)
      } catch (error) {
        console.error('聚焦窗口失败:', error)
      }
    },

    async openDevTools(windowId = null) {
      if (!this.isElectron) return

      try {
        if (windowId) {
          await window.electronAPI.openDevToolsForWindow(windowId)
        } else {
          await window.electronAPI.openDevTools()
        }
      } catch (error) {
        console.error('打开开发者工具失败:', error)
      }
    },

    async closeAllWindows() {
      if (!this.isElectron) return

      try {
        const windowList = [...this.windows]
        for (const win of windowList) {
          if (win.type !== 'main') {
            await this.closeWindow(win.id)
          }
        }
      } catch (error) {
        console.error('关闭所有窗口失败:', error)
      }
    },

    async initialize() {
      if (this.isElectron) {
        await this.refreshWindowsList()
        // setInterval(() => this.refreshWindowsList(), 3000)
      }
    },
  },
})
